package com.seamtop.cuber.web.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seamtop.cuber.common.base.DataObject;
import com.seamtop.cuber.common.entriy.CuberModule;
import com.seamtop.cuber.common.entriy.CuberUnit;
import com.seamtop.cuber.web.dao.ViewDao;
import com.seamtop.cuber.web.service.ViewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by feng on 2015/10/28.
 */
@Service
public class ViewServiceImpl implements ViewService{

    @Autowired
    private ViewDao viewDao;

    @Override
    public void addView(List<CuberModule> moduleList) {
        for(int i=0;i<moduleList.size();i++){
            CuberModule module = moduleList.get(i);
            System.out.println("spanType:"+module.getSpanType());
        }
        viewDao.addView(moduleList);
    }

    public void loadCuberView(){
        HashMap<Integer,TreeMap<Integer,List<CuberModule>>> cuberViewMap = new HashMap<Integer, TreeMap<Integer, List<CuberModule>>>();
        List<CuberModule> moduleList = viewDao.findCuberModuleList();
        for(int i=0;i<moduleList.size();i++){
            JSONObject jsonObject = new JSONObject();
            CuberModule module = moduleList.get(i);
            //dataval init
            jsonObject.put("displayType",module.getDisplayType());
            jsonObject.put("spanType",module.getSpanType());
            JSONArray factsArray = new JSONArray();
            String [] temp = module.getFacts().split(",");
            for(int j=0;j<temp.length;j++){
                factsArray.add(temp[j]);
            }
            jsonObject.put("facts",factsArray);
            module.setDataVal(jsonObject.toJSONString());
            int pageId = module.getPageId();
            TreeMap<Integer,List<CuberModule>> unitMap = cuberViewMap.get(pageId);
            if(unitMap == null){
                unitMap = new TreeMap<Integer, List<CuberModule>>();
                cuberViewMap.put(pageId,unitMap);
            }

            int order = module.getUnitOrder();
            List<CuberModule> tempList = unitMap.get(order);
            if(tempList == null){
                tempList = new ArrayList<CuberModule>();
                unitMap.put(order,tempList);
            }
            tempList.add(module);
        }
        DataObject.setCuberViewMap(cuberViewMap);
    }

    @Override
    public void deleteView(HashMap<String, Object> paramsMap) {
        viewDao.deleteView(paramsMap);
    }
}
